class AIChatSystem {
    constructor() {
        this.apiEndpoint = 'http://localhost:5000/api/chat'; // 假设后端API地址
        this.chatMessages = document.getElementById('chat-messages');
        this.chatForm = document.getElementById('chat-form');
        this.userInput = document.getElementById('user-input');
        
        this.initEventListeners();
        this.addSystemMessage('欢迎使用中医智能辅助系统，请输入中药/方剂名称或提问。');
    }

    initEventListeners() {
        // 表单提交
        this.chatForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleUserInput();
        });

        // 知识库导航点击
        document.querySelectorAll('.knowledge-list a').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                this.userInput.value = link.dataset.query;
                this.handleUserInput();
            });
        });
    }

    handleUserInput() {
        const query = this.userInput.value.trim();
        if (!query) return;

        this.addUserMessage(query);
        this.userInput.value = '';
        
        this.showTypingIndicator();
        this.sendQueryToAPI(query);
    }

    async sendQueryToAPI(query) {
        try {
            const response = await fetch(this.apiEndpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ query })
            });

            if (!response.ok) {
                throw new Error(`API请求失败: ${response.status}`);
            }

            const data = await response.json();
            this.removeTypingIndicator();
            
            if (data.systemMessage) {
                this.addSystemMessage(data.systemMessage);
            }
            
            if (data.knowledgeData) {
                this.addKnowledgeData(data.knowledgeData);
            }
            
            if (data.aiResponse) {
                this.addAIMessage(data.aiResponse);
            }
        } catch (error) {
            this.removeTypingIndicator();
            this.addErrorMessage(`系统错误: ${error.message}`);
            console.error('API请求错误:', error);
        }
    }

    addUserMessage(text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message user-message';
        messageDiv.innerHTML = `<strong>您:</strong><p>${text}</p>`;
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    addAIMessage(text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message ai-message';
        messageDiv.innerHTML = `<strong>AI助手:</strong><p>${text}</p>`;
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    addSystemMessage(text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message system-message';
        messageDiv.textContent = text;
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    addErrorMessage(text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message system-message';
        messageDiv.style.color = 'var(--error-color)';
        messageDiv.textContent = text;
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    addKnowledgeData(data) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message system-message';
        
        let html = `<strong>知识库数据:</strong><ul>`;
        html += `<li>名称: ${data.name}</li>`;
        html += `<li>类型: ${data.type.join(', ')}</li>`;
        
        if (data.details) {
            html += `<li>组成: ${data.details}</li>`;
        }
        
        if (data.relations && data.relations.length > 0) {
            html += `<li>关联信息: <ul>`;
            data.relations.forEach(rel => {
                html += `<li>${rel.relation_type}: ${rel.related_name} (${rel.related_type.join(', ')})</li>`;
            });
            html += `</ul></li>`;
        }
        
        html += `</ul>`;
        messageDiv.innerHTML = html;
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    showTypingIndicator()
